#include "stdafx.h"
#include "compression.h"

void compression (long double res, int *pos, char *sym, int n)
{
	ofstream file;
	file.open("C:\\answer.txt");
	long double *low = new long double [n];
	long double *high = new long double [n];
	float sum = 0;
	
	for (int i = 0; i < n; i++)
		sum += pos[i];
	
	low[0] = 0; high[n-1] = 1;
	for (int i = 1; i < n; i++)
	{
		low[i] = high[i-1] = low[i-1] + pos[i-1]/sum;
	}

	long double l1 = 0, h1 = 1, l2, h2; 

	for (int i = 0; i < sum; i++)
	{
		for (int j = 0; j<sum, pos[j] != 0; j++)
		{
			l2 = l1 + low[j]*(h1 - l1);
			h2 = l1 + high[j]*(h1 - l1);
			if ((res > l2) && (res < h2))
			{
				file << sym[j];
				l1 = l2;
				h1 = h2;
				break;
			}
		}
	}

}

long double compression (ifstream &file, int *pos, char *sym, int n)
{
	long double *low = new long double [n];
	long double *high = new long double [n];
	float sum = 0;
	
	for (int i = 0; i < n; i++)
		sum += pos[i];
	
	low[0] = 0; high[n-1] = 1;
	for (int i = 1; i < n; i++)
	{
		low[i] = high[i-1] = low[i-1] + pos[i-1]/sum;
	}

	long double l1 = 0, h1 = 1, l2, h2; 
	int cur;
	file.seekg(0);

	for (int i = 0; i < sum; i++)
	{
		char next = file.peek();
		for (int j = 0; j < n; j++)
		{
			if (next == sym[j])
			{
				cur = j;
				break;
			}
		}
		l2 = l1 + low[cur]*(h1 - l1);
		h2 = l1 + high[cur]*(h1 - l1);
		l1 = l2; 
		h1 = h2;
		file.seekg(i+1);
	}

	return (l2 + 0.5*(h2 - l2) );

};